const puppeteer = require("puppeteer");
const moment = require("moment");
const getId = require("../../../common/getid");

const {createMobile, config} = require("../../../common/mobile");
const {
    info,
    saveFile,
    logging,
    timeout,
    reporter,
    pickOne,
    waitSelector
} = require("../../../common/util");

const name = "nl_vd";
const today = moment().format("YYYY-MM-DD");
const logdir = `./logs/${today}/nl/other/${info.deviceid}`;

const r = reporter(name);
const logger = logging(name, logdir);

const postData = {
    operator_code: JSON.parse(info.meta).operator_code,
    task_id: "f_nl_vd"
};

(async () => {

    logger.info("start");
    let value = await getId(postData);
    value = JSON.parse(value);

    logger.info("get _id success");

    if (value.code !== 0) {
        logger.error("no click id");
        return;
    }

    const links = [
        `http://offer.edigitaloffer.com/aff/track?token=CsyWQl&offer=131&cid=${value.data}&pid=${value.data}`
    ];

    const browser = await puppeteer.launch(config);
    const [page] = await browser.pages();

    // page.setExtraHTTPHeaders({
    //   "Upgrade-Insecure-Requests": "1",
    //   "Accept-Language":
    //     "zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2"
    // });

    logger.info("start chrome success");

    const m = await createMobile(page);

    await m._page.setRequestInterception(true);

    //sub status linstener
    m._page.on("response", response => {
        let url = response.url();
        let status = response.status();

        if (url.startsWith("http")) {
            logger.info(`${response.request().method()}`, status, url);
        }

        if (url.startsWith(`http://mes.popsanime.com/?sd`)) {
            logger.info("success");
            r.s("success");
        }

        if (url.startsWith("http://google.com")) {
            r.w("failure", url);
            m.close();
        }
    });

    m._page.on('request', interceptedRequest => {
        if (interceptedRequest.url().endsWith('adsqnt.com/nl/powerland/pm3a/img/bg.png')) {
            interceptedRequest.abort();
        } else {
            interceptedRequest.continue();
        }
    });

    logger.info("start task");

    //开始
    try {
        r.i("start");

        logger.info("start");

        await m.get(pickOne(links));

        // await waitSelector(() => {
        await m._page.waitForSelector("a[id='btn-continue']", {timeout: 2 * 60 * 1000});
        // }, 4);

        await m.sleep(parseInt(Math.random() * 1000 + 1000));

        await m.evaluate(() => {
            document.getElementById("btn-continue").click();
        });

        // await m._page.waitForSelector("button[data-testid='payButton']", {timeout: 2 * 60 * 1000})

        // await m.sleep(parseInt(Math.random() * 1000 + 1000));

        // await m.tapElement("button[data-testid='payButton']");

        //保存页面
        saveFile(`${logdir}/1.html`, await m._page.content());

        await m.sleep(60 * 60 * 1000);

        logger.info("save1");

        logger.info("end");

        r.i("end");
    } catch (e) {

        saveFile(`${logdir}/error.html`, await m._page.content());

        r.e(e + "");

        logger.error(e);
    } finally {
        await m.close();
    }
    await browser.close();
})();
